package org.com.system.util.processor;

import java.io.BufferedReader;
import java.lang.reflect.Field;
import java.sql.Clob;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import oracle.sql.CHAR;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.dbutils.RowProcessor;
import org.com.system.util.sql.SQLUtils;

public class DefaultRowProcessor implements RowProcessor {

	public Object[] toArray(ResultSet result) throws SQLException {
		return null;
	}

	public <T> T toBean(ResultSet result, Class<T> model) throws SQLException {
		T entity=null;
		try{
			entity=model.newInstance();
		    Field[] fields=model.getFields();
		    String fieldName=null;
		    Class<?> type=null;
		    for(Field field:fields){
		    	fieldName=field.getName();
		    	type=field.getType();
		    	if(Long.class.equals(type)){
		    		BeanUtils.setProperty(entity,fieldName,result.getLong(SQLUtils.addUnderline(fieldName)));
		    	}else if(Integer.class.equals(type)||int.class.equals(type)||short.class.equals(type)){
		    		BeanUtils.setProperty(entity,fieldName,result.getInt(SQLUtils.addUnderline(fieldName)));
		    	}else if(String.class.equals(type)||CHAR.class.equals(type)){
		    		BeanUtils.setProperty(entity,fieldName,result.getString(SQLUtils.addUnderline(fieldName)));
		    	}else if(Clob.class.equals(type)){
		    		BeanUtils.setProperty(entity,fieldName,getClobString(result.getClob((SQLUtils.addUnderline(fieldName)))));
		    	}
		    }
		}catch(Exception e){
			e.printStackTrace();
		}
		return entity;
	}

	public <T> List<T> toBeanList(ResultSet result, Class<T> model)throws SQLException {
		List<T> data=new ArrayList<T>();
		while(result.next()){
			data.add(toBean(result, model));
		}
		return data;
	}

	public Map<String, Object> toMap(ResultSet result) throws SQLException {
		return null;
	}
	
	public String getClobString(Clob clob){
		BufferedReader reader=null;
		StringBuffer stber=null;
		try {
			reader=new BufferedReader(clob.getCharacterStream());
			stber=new StringBuffer();
			while(reader.ready()){
				stber.append(reader.readLine());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return stber.toString();
	}

}
